package com.usermanage.controller;

import com.change.Enum.EnvironmentEnum;
import com.change.Service.AirSoftService;
import com.ordercore.Util.ResponseData.ResponseData;
import com.pinza.Bean.NonStandardLibraryBean;
import com.pinza.Common.NonStandardLibraryIOC;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.*;
import com.usermanage.beanParam.ContractBean;
import com.usermanage.beanParam.ContractRealTimePriceBean;
import com.usermanage.beanParam.MessageBean;
import com.usermanage.beanParam.UserBean;
import com.usermanage.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/contractRealTime")
public class ContractRealTimeController {

    @Resource
    private ContractRealTimePriceService contractRealTimePriceService;
    @Resource
    private MessageService messageService;
    @Resource
    private UserService userService;

    /**
     *
     * @param id
     * @param sku_code
     * @param airSoft_id
     * @param type
     * @return
     */
    @RequestMapping("/completion.json")
    public JsonData completionSku(String id, String sku_code, String airSoft_id, String type) {
        if (type.equals("sku")) {
            Map map = new HashMap();
            map.put("sku_code",sku_code);
            map.put("airSoft_id",airSoft_id);
          return contractRealTimePriceService.syncSku(map,"update");
        } else if (type.equals("nsl")) {
            ResponseData responseData = NonStandardLibraryIOC.getNonStandardLibraryDetail(sku_code);
            NonStandardLibraryBean nonStandardLibraryBean = (NonStandardLibraryBean) responseData.getData();
            nonStandardLibraryBean.setAir_soft_id(airSoft_id);
            try {
                NonStandardLibraryIOC.nonStandardLibraryUpdate(nonStandardLibraryBean);
                return JsonData.success();
            } catch (Exception e) {
                return JsonData.fail("id为：" + id + " ,编号为：" + sku_code + "  的SKU,非标库修改失败，" + e.toString());
            }
        } else {
            return JsonData.fail("非法参数");
        }
    }

    @RequestMapping("/cancel.json")
    public JsonData cancelSku(String sku_code) {
        Map map = new HashMap();
        map.put("sku_code",sku_code);
        return contractRealTimePriceService.syncSku(map,"cancel");
    }

    @RequestMapping(value = "/priceAdd.json")
    public JsonData realTimePrice(String id, String contract_id, String sku_contract_price) throws Exception {
        Optional<ContractRealTimePriceBean> optional = contractRealTimePriceService.findById(Integer.valueOf(id));
        ContractRealTimePriceBean bean = optional.get();

        int count = contractRealTimePriceService.getSkuBySkuCodeAndContractId(bean.getSku_code(), bean.getContract_id(), "00");
        if (count > 0) {
            return JsonData.fail("该条SKU信息已经同步过了!");
        }
        bean.setStatus("00");
        bean.setSku_contract_price(sku_contract_price);
        bean.setUpdate_time(DateUtil.getNowTimeString());
        //如果合同为集栋内部合同，则同步至PM
        if (contract_id.equals("15")) {
            String jsonBean = StringUtil.ObjectToJson(bean);
            Map mapBean = StringUtil.JsonToMap(jsonBean);
            mapBean.put("type", "add");
            mapBean.put("oprType", "010");
            String param = StringUtil.ObjectToJson(mapBean);
            messageService.rabbitMq("syncChange", "syncKey", param);
            return contractRealTimePriceService.save(bean);
        } else {
            bean.setSku_id(bean.getSku_system_code());
            sendMessage(bean);
            return JsonData.success(contractRealTimePriceService.save(bean));
        }

    }

    @RequestMapping(value = "/Update.json", method = RequestMethod.POST)
    public JsonData realTimePriceUpdate(@Valid ContractRealTimePriceBean bean) {
        List<ContractRealTimePriceBean> list = contractRealTimePriceService.findListBySkuCode(bean.getSku_code());
        StringBuffer buffer = new StringBuffer();
        for (ContractRealTimePriceBean contractRealTimePriceBean : list) {
            buffer.append(contractRealTimePriceBean.getId()).append(",");
        }
        String bf = buffer.substring(0, buffer.length() - 1);
        String[] arry = bf.split(",");
        for (int i = 0; i < arry.length; i++) {
            ContractRealTimePriceBean contractBean = new ContractRealTimePriceBean();
            contractBean.setId(Integer.valueOf(arry[i]));
            contractRealTimePriceService.save(bean);
        }
        return JsonData.success();

    }

    @RequestMapping(value = "/realTimeJsonByContractId.json")
    public JsonData realTimeJsonByContractId(String key, String contract_id, String page, String size, String type) throws Exception {
        if (StringUtils.isBlank(page)) {
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(size)) {
            size = StaticUtil.sizeCount;
        }
        List<ContractRealTimePriceBean> list = contractRealTimePriceService.findAllList(key, contract_id, page, size, type);
        int count = contractRealTimePriceService.getAllListCount(key, contract_id, type);
        Map resultMap = new HashMap();
        resultMap.put("list", list);
        resultMap.put("total", count);
        return JsonData.success(resultMap);
    }

    @RequestMapping(value = "/dataCenterUpdate.json", method = RequestMethod.POST)
    @Transactional
    public JsonData updateSku(String obj, String contract_price, String contract_id, String sku_code) throws Exception {
        Map map = new HashMap();
        if (StringUtils.isNotBlank(obj)) {
            map = StringUtil.JsonToMap(obj);
        }
        List<ContractRealTimePriceBean> contractRealTimePriceBeans = contractRealTimePriceService.findListBySkuCode(sku_code);
        if (contractRealTimePriceBeans.size() == 0) {
            return JsonData.success();
        }
        if (StringUtils.isNotBlank(contract_id)) {
            List<ContractRealTimePriceBean> list = contractRealTimePriceService.getSkuBySkuCodeAndContractIdDetail(sku_code, contract_id);
            if (list.size() > 0) {
                ContractRealTimePriceBean contractRealTimePriceBean = list.get(0);
                contractRealTimePriceBean.setSku_contract_price(contract_price);
                contractRealTimePriceService.update(contractRealTimePriceBean);
            }
        } else {
            for (ContractRealTimePriceBean contractRealTimePriceBean : contractRealTimePriceBeans) {
                contractRealTimePriceBean.setSku_official_price(map.get("sku_official_price").toString());
                contractRealTimePriceBean.setSku_cost_price(map.get("sku_cost_price").toString());
                contractRealTimePriceBean.setSku_brand(map.get("sku_brand").toString());
                contractRealTimePriceBean.setSku_unit(map.get("sku_unit").toString());
                contractRealTimePriceBean.setSku_name(map.get("sku_name").toString());
                contractRealTimePriceBean.setSku_lead_time(map.get("sku_lead_time").toString());
                if (map.get("sku_pic_url") != null || StringUtils.isNotBlank(map.get("sku_pic_url").toString())) {
                    contractRealTimePriceBean.setSku_pic_url(map.get("sku_pic_url").toString());
                }
                if (map.get("sku_model") != null || StringUtils.isNotBlank(map.get("sku_model").toString())) {
                    contractRealTimePriceBean.setSku_model(map.get("sku_model").toString());
                }
                if (map.get("sku_slug_set") != null || StringUtils.isNotBlank(map.get("sku_slug_set").toString())) {
                    contractRealTimePriceBean.setSku_slug_set(map.get("sku_slug_set").toString());
                }
                if (contract_price != null) {
                    contractRealTimePriceBean.setSku_contract_price(contract_price);
                }
                contractRealTimePriceService.update(contractRealTimePriceBean);
            }
        }
        return JsonData.success();
//        List<ContractRealTimePriceBean> list = contractRealTimePriceService.getSkuBySkuCodeAndContractIdDetail(sku_code, "15");
//        if (list.size() > 0) {
//            ContractRealTimePriceBean contractRealTimePriceBean = list.get(0);
//            if (map.size() == 0) {
//                map.put("sku_code", sku_code);
//                map.put("sku_name", contractRealTimePriceBean.getSku_name());
//                map.put("sku_unit", contractRealTimePriceBean.getSku_unit());
//                map.put("sku_brand", contractRealTimePriceBean.getSku_brand());
//                map.put("sku_slug_set", contractRealTimePriceBean.getSku_slug_set());
//                map.put("sku_cost_price", contractRealTimePriceBean.getSku_contract_price());
//                map.put("sku_official_price", contractRealTimePriceBean.getSku_official_price());
//                map.put("sku_system_code", contractRealTimePriceBean.getSku_system_code());
//                map.put("sku_lead_time", contractRealTimePriceBean.getSku_lead_time());
//                map.put("sku_model", contractRealTimePriceBean.getSku_model());
//            }
//            map.put("type", "update");
//            map.put("air_soft_id", contractRealTimePriceBean.getSku_id());
//            if (contract_price != null) {
//                map.put("sku_contract_price", contract_price);
//            } else {
//                map.put("sku_contract_price", contractRealTimePriceBean.getSku_contract_price());
//            }
//            String data = StringUtil.ObjectToJson(map);
//            JsonData result = AirSoftService.airSoftEdit(data, StaticUtil.environmentEnum);
//            return result;
//            String result = HttpUtil.post(StaticUtil.changeCenter+"/airSoft/edit.json", data);
//            Map mapResult = StringUtil.JsonToMap(result);
//            if (mapResult.get("ret").equals(true)) {
//                return JsonData.success();
//            } else {
//                return JsonData.fail("首信同步错误");
//            }
//        } else {
//            return JsonData.success();
//        }
    }

    /**
     * 数据中心新添的SKU同步到实时合同中，状态为99
     */
    @RequestMapping(value = "/syncSku.json", method = RequestMethod.POST)
    public JsonData syncSku(String obj) {
        Map map = StringUtil.JsonToMap(obj);
//        if (StringUtils.isNotBlank(obj)) {
//            map = StringUtil.JsonToMap(obj);
//        }

        return JsonData.success();
    }

    public void sendMessage(ContractRealTimePriceBean bean) throws Exception {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        MessageBean messageBean = new MessageBean();
        messageBean.setMessage_no(bean.getSku_code());
        messageBean.setMessage_type("msg008");
        messageBean.setMessage_body(StaticUtil.company + "  的  " + userDetail.getUsername() + "  新增了一条SKU，名称为：  " + bean.getSku_name() + "  ，编号为：  " + bean.getSku_code() + "  ，请及时查看。");
        messageBean.setMessage_creater(String.valueOf(userDetail.getId()));
        List<UserBean> userBeans = userService.findUserByCompanyId(userDetail.getCompany_id());
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < userBeans.size(); i++) {
            buffer.append(userBeans.get(i).getId()).append(",");
        }
        messageBean.setMessage_sendee(buffer.toString());
        messageBean.setMessage_status("99");
        messageService.send(messageBean);
    }
}
